class TrustLeaderboardManager {
  constructor() {
    this.leaderboardData = []
    this.currentUser = null
    this.cache = new Map()
    this.cacheExpiry = 5 * 60 * 1000 // 5分钟缓存
  }
  
  // 获取排行榜数据
  async getLeaderboard(options = {}) {
    const {
      period = 'week',
      limit = 20,
      offset = 0,
      useCache = true
    } = options
    
    const cacheKey = `leaderboard_${period}_${limit}_${offset}`
    
    // 检查缓存
    if (useCache && this.cache.has(cacheKey)) {
      const cached = this.cache.get(cacheKey)
      if (Date.now() - cached.timestamp < this.cacheExpiry) {
        return cached.data
      }
    }
    
    try {
      // 生成模拟数据
      const data = await this.generateMockLeaderboardData(period, limit, offset)
      
      // 缓存数据
      this.cache.set(cacheKey, {
        data: data,
        timestamp: Date.now()
      })
      
      return data
    } catch (error) {
      console.error('Failed to get leaderboard:', error)
      throw error
    }
  }
  
  // 生成模拟排行榜数据
  async generateMockLeaderboardData(period, limit, offset) {
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const users = this.generateMockUsers(limit + offset)
    const leaderboard = users.slice(offset, offset + limit)
    const currentUser = this.getCurrentUser()
    const currentUserRank = this.calculateUserRank(currentUser, users)
    
    return {
      leaderboard: leaderboard,
      currentUserRank: currentUserRank,
      totalUsers: users.length,
      averageTrust: this.calculateAverageTrust(users),
      maxTrust: Math.max(...users.map(u => u.trustValue)),
      hasMore: offset + limit < users.length
    }
  }
  
  // 生成模拟用户数据
  generateMockUsers(count) {
    const users = []
    const names = [
      '信任守护者', '合作达人', '诚信之星', '可靠伙伴', '真诚朋友',
      '信任大师', '合作专家', '诚信模范', '可靠盟友', '真诚伙伴',
      '信任使者', '合作先锋', '诚信典范', '可靠战友', '真诚盟友',
      '信任导师', '合作领袖', '诚信楷模', '可靠朋友', '真诚战友'
    ]
    
    const avatars = ['👤', '👨', '👩', '🧑', '👨‍💼', '👩‍💼', '👨‍🎓', '👩‍🎓', '👨‍🔬', '👩‍🔬']
    const titles = ['信任专家', '合作达人', '诚信模范', '可靠伙伴', '真诚朋友', '普通用户']
    const tags = ['新手', '专家', '大师', '传奇', 'VIP', '认证']
    const badges = [
      { id: 'trust_master', icon: '🏆', text: '信任大师', type: 'achievement' },
      { id: 'cooperation_king', icon: '🤝', text: '合作之王', type: 'special' },
      { id: 'vip_member', icon: '💎', text: 'VIP会员', type: 'vip' }
    ]
    
    for (let i = 0; i < count; i++) {
      const trustValue = Math.floor(Math.random() * 100)
      const trend = Math.floor(Math.random() * 21) - 10 // -10 到 +10
      const status = ['online', 'offline', 'busy', 'away'][Math.floor(Math.random() * 4)]
      
      users.push({
        id: `user_${i + 1}`,
        name: names[i % names.length] + (i > names.length - 1 ? ` ${Math.floor(i / names.length) + 1}` : ''),
        avatar: avatars[i % avatars.length],
        title: titles[Math.floor(Math.random() * titles.length)],
        trustValue: trustValue,
        trend: trend,
        status: status,
        tags: this.getRandomTags(tags),
        badges: this.getRandomBadges(badges),
        isCurrentUser: i === 0, // 第一个用户设为当前用户
        highlight: trustValue >= 90
      })
    }
    
    // 按信任值排序
    return users.sort((a, b) => b.trustValue - a.trustValue)
  }
  
  // 获取随机标签
  getRandomTags(allTags) {
    const count = Math.floor(Math.random() * 3) + 1
    const shuffled = [...allTags].sort(() => 0.5 - Math.random())
    return shuffled.slice(0, count)
  }
  
  // 获取随机徽章
  getRandomBadges(allBadges) {
    const count = Math.floor(Math.random() * 2) + 1
    const shuffled = [...allBadges].sort(() => 0.5 - Math.random())
    return shuffled.slice(0, count)
  }
  
  // 获取当前用户
  getCurrentUser() {
    if (this.currentUser) return this.currentUser
    
    // 从本地存储获取用户信息
    try {
      const userData = uni.getStorageSync('currentUser')
      if (userData) {
        this.currentUser = JSON.parse(userData)
      } else {
        // 创建默认用户
        this.currentUser = {
          id: 'current_user',
          name: '我',
          avatar: '👤',
          title: '普通用户',
          trustValue: 50,
          trend: 0,
          status: 'online',
          tags: ['新手'],
          badges: [],
          isCurrentUser: true
        }
      }
    } catch (error) {
      console.error('Failed to get current user:', error)
      this.currentUser = {
        id: 'current_user',
        name: '我',
        avatar: '👤',
        title: '普通用户',
        trustValue: 50,
        trend: 0,
        status: 'online',
        tags: ['新手'],
        badges: [],
        isCurrentUser: true
      }
    }
    
    return this.currentUser
  }
  
  // 计算用户排名
  calculateUserRank(user, allUsers) {
    if (!user) return null
    
    const sortedUsers = [...allUsers].sort((a, b) => b.trustValue - a.trustValue)
    const rank = sortedUsers.findIndex(u => u.id === user.id) + 1
    
    if (rank === 0) return null
    
    return {
      rank: rank,
      name: user.name,
      avatar: user.avatar,
      trustValue: user.trustValue,
      change: this.calculateRankChange(user.id, rank)
    }
  }
  
  // 计算排名变化
  calculateRankChange(userId, currentRank) {
    try {
      const lastRank = uni.getStorageSync(`lastRank_${userId}`)
      if (lastRank) {
        const change = lastRank - currentRank
        // 保存当前排名
        uni.setStorageSync(`lastRank_${userId}`, currentRank)
        return change
      } else {
        // 首次记录
        uni.setStorageSync(`lastRank_${userId}`, currentRank)
        return 0
      }
    } catch (error) {
      console.error('Failed to calculate rank change:', error)
      return 0
    }
  }
  
  // 计算平均信任值
  calculateAverageTrust(users) {
    if (users.length === 0) return 0
    const total = users.reduce((sum, user) => sum + user.trustValue, 0)
    return Math.round(total / users.length)
  }
  
  // 更新用户信任值
  updateUserTrust(userId, newTrustValue) {
    try {
      const userData = uni.getStorageSync('currentUser')
      if (userData) {
        const user = JSON.parse(userData)
        user.trustValue = Math.max(0, Math.min(100, newTrustValue))
        uni.setStorageSync('currentUser', JSON.stringify(user))
        this.currentUser = user
        
        // 清除缓存
        this.clearCache()
        
        return true
      }
    } catch (error) {
      console.error('Failed to update user trust:', error)
    }
    return false
  }
  
  // 获取用户详情
  async getUserDetails(userId) {
    try {
      // 这里应该从服务器获取用户详情
      // 现在返回模拟数据
      return {
        id: userId,
        name: '用户详情',
        avatar: '👤',
        title: '信任专家',
        trustValue: 85,
        joinDate: '2024-01-01',
        totalInteractions: 150,
        trustHistory: this.generateTrustHistory(),
        achievements: this.generateAchievements(),
        recentActivity: this.generateRecentActivity()
      }
    } catch (error) {
      console.error('Failed to get user details:', error)
      throw error
    }
  }
  
  // 生成信任历史
  generateTrustHistory() {
    const history = []
    const days = 30
    
    for (let i = days; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      
      history.push({
        date: date.toISOString().split('T')[0],
        trustValue: 50 + Math.floor(Math.random() * 50),
        interactions: Math.floor(Math.random() * 10) + 1
      })
    }
    
    return history
  }
  
  // 生成成就
  generateAchievements() {
    return [
      {
        id: 'first_trust',
        name: '初次信任',
        description: '完成第一次信任互动',
        icon: '🤝',
        unlocked: true,
        unlockedDate: '2024-01-01'
      },
      {
        id: 'trust_master',
        name: '信任大师',
        description: '信任值达到90以上',
        icon: '🏆',
        unlocked: false,
        unlockedDate: null
      },
      {
        id: 'cooperation_king',
        name: '合作之王',
        description: '完成100次合作',
        icon: '👑',
        unlocked: false,
        unlockedDate: null
      }
    ]
  }
  
  // 生成最近活动
  generateRecentActivity() {
    const activities = [
      '与用户A建立了信任关系',
      '完成了信任挑战',
      '获得了信任徽章',
      '参与了信任讨论',
      '帮助了新用户'
    ]
    
    const recent = []
    for (let i = 0; i < 5; i++) {
      recent.push({
        id: `activity_${i + 1}`,
        description: activities[Math.floor(Math.random() * activities.length)],
        timestamp: Date.now() - (i * 24 * 60 * 60 * 1000), // 过去几天
        type: 'trust'
      })
    }
    
    return recent
  }
  
  // 清除缓存
  clearCache() {
    this.cache.clear()
  }
  
  // 获取排行榜统计
  getLeaderboardStats(period = 'week') {
    return {
      totalUsers: 1000,
      averageTrust: 65,
      maxTrust: 100,
      minTrust: 0,
      trustDistribution: {
        high: 150,    // >= 80
        medium: 500,  // 50-79
        low: 300,     // 20-49
        broken: 50    // < 20
      },
      period: period
    }
  }
  
  // 搜索用户
  async searchUsers(query, limit = 10) {
    try {
      // 模拟搜索
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const allUsers = this.generateMockUsers(100)
      const filtered = allUsers.filter(user => 
        user.name.toLowerCase().includes(query.toLowerCase()) ||
        user.title.toLowerCase().includes(query.toLowerCase())
      )
      
      return filtered.slice(0, limit)
    } catch (error) {
      console.error('Failed to search users:', error)
      throw error
    }
  }
  
  // 获取用户排名历史
  async getUserRankHistory(userId, period = 'month') {
    try {
      const history = []
      const days = period === 'week' ? 7 : period === 'month' ? 30 : 365
      
      for (let i = days; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        
        history.push({
          date: date.toISOString().split('T')[0],
          rank: Math.floor(Math.random() * 100) + 1,
          trustValue: 50 + Math.floor(Math.random() * 50)
        })
      }
      
      return history
    } catch (error) {
      console.error('Failed to get rank history:', error)
      throw error
    }
  }
}

export default new TrustLeaderboardManager()

